package mn.idax.exchange.otc.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: dison
 * @Date: 2018/7/27 16:43
 * @Description: 二维码工具类
 * @//
 *
 */
public class QrCodeUtils {

    /**
     *
     * 功能描述:
     *
     * @param: width 二维码宽度
     * @param: height 二维码高度
     * @param: content 二维码内容
     * @return: BitMatrix
     * @auther: dison
     * @date: 2018/7/27 16:51
     */
    public static BitMatrix createMatrix(int width, int height, String content) throws WriterException {
        Map<EncodeHintType,Object> config = new HashMap<>();
        config.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        config.put(EncodeHintType.MARGIN, 0);
        return new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,height,config);
    }

    /**
     *
     * 功能描述:
     *
     * @param: width 二维码宽度
     * @param: height 二维码高度
     * @param: content 二维码内容
     * @return: BitMatrix
     * @auther: dison
     * @date: 2018/7/27 16:51
     */
    public static BufferedImage createBufImage(int width, int height, String content) throws WriterException {
        BitMatrix bitMatrix = createMatrix(width,height,content);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

    /**
     *
     * 功能描述:
     *          输出二维码流
     * @param: width 二维码宽度
     * @param: height 二维码高度
     * @param: content 二维码内容
     * @param: picType 二维码图片类型
     * @return: BitMatrix
     * @auther: dison
     * @date: 2018/7/27 16:51
     */
    public static void writeToStream(int width, int height, String content, String picType, OutputStream out) throws WriterException, IOException {
        BitMatrix bitMatrix = createMatrix(width,height,content);
        MatrixToImageWriter.writeToStream(bitMatrix,picType,out);
    }

    public static void main(String[] args) {
    }
}
